<template>
  <div class="user-info">
    <h2>用户信息</h2>
    <div v-if="user">
      <div v-if="!isEditing && !isEditingPassword">
        <img :src="getCreatorAvatarUrl(user.avatar)" alt="User Avatar" class="user-avatar" />
        <p><strong>昵称:</strong> {{ user.nickname }}</p>
        <p><strong>用户ID:</strong> {{ user.id }}</p>
        <button type="button" @click="toggleEdit">修改信息</button>
        <button type="button" @click="handleEditPassword">修改密码</button>
      </div>
      <div v-else-if="isEditing">
        <form @submit.prevent="handleEditMessage">
          <table>
            <tr>
              <th>ID</th>
              <td>{{ user.id }}</td>
            </tr>
            <tr>
              <th>昵称</th>
              <td>
                <input type="text" v-model="user.nickname" required />
              </td>
            </tr>
            <tr>
              <th>头像</th>
              <td>
                <input type="file" @change="onFileChange" accept="image/*" />
                <img v-if="user.avatar" :src="getCreatorAvatarUrl(user.avatar)" alt="User Avatar" class="user-avatar-preview" />
              </td>
            </tr>
          </table>
          <button type="submit">保存</button>
          <button type="button" @click="toggleEdit">取消</button>
        </form>
      </div>
      <div v-else-if="isEditingPassword">
        <form @submit.prevent="updatePassword">
          <table>
            <tr>
              <th>旧密码</th>
              <td>
                <input type="password" v-model="oldPassword" required ref="oldPasswordInput" />
              </td>
            </tr>
            <tr>
              <th>新密码</th>
              <td>
                <input type="password" v-model="newPassword" required />
              </td>
            </tr>
            <tr>
              <th>确认新密码</th>
              <td>
                <input type="password" v-model="confirmNewPassword" required />
              </td>
            </tr>
          </table>
          <button type="submit">保存</button>
          <button type="button" @click="cancelEditPassword">取消</button>
        </form>
      </div>
    </div>
    <div v-else>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import '@/styles/userStyles.less';

export default {
  name: 'UserPage',
  data() {
    return {
      user: null,
      selectedFile: null,
      selectedFileName: '', // 新增属性，用于存储文件名
      isEditing: false,
      isEditingPassword: false,
      oldPassword: '',
      newPassword: '',
      confirmNewPassword: ''
    };
  },
  created() {
    this.fetchUserData();
  },
  methods: {
    async fetchUserData() {
      try {
        const userId = localStorage.getItem('userId');
        if (!userId) {
          throw new Error('用户ID未找到');
        }

        const response = await axios.get(`http://localhost:8000/getuserbyid?id=${userId}`);
        this.user = response.data;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        alert('获取用户信息失败，请重试。');
      }
    },
    
    getCreatorAvatarUrl(avatarPath) {
      if (avatarPath.startsWith('data:')) {
        return avatarPath;
      }

      if (avatarPath.startsWith('http://localhost:5000/')) {
        avatarPath = avatarPath.replace('http://localhost:5000/', '');
      }

      if (!avatarPath.startsWith('http')) {
        avatarPath = require(`@/assets/upload/${avatarPath}`);
      }

      return avatarPath;
    },

    onFileChange(event) {
      this.selectedFile = event.target.files[0];
      if (this.selectedFile) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.user.avatar = e.target.result;
        };
        reader.readAsDataURL(this.selectedFile);
        this.selectedFileName = this.selectedFile.name; // 存储文件名
      }
    },
    
    async uploadAvatar(file) {
      console.log('执行了文件上传操作');
      const formData = new FormData();
      formData.append('file', file);

      try {
        const response = await axios.post('http://localhost:8000/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        alert('文件上传成功！');
        return response.data.path; // 假设服务器返回的响应中包含文件路径
      } catch (error) {
        console.error('上传文件失败:', error);
        alert('上传文件失败，请重试。');
        return null;
      }
    },
    async handleEditMessage() {
      console.log('handleEditMessage called'); // 调试信息
      console.log('this.selectedFileName:', this.selectedFileName)
      try {
        let avatarPath = this.user.avatar;
        
        if (this.selectedFile) {
          console.log('this.selectedFile:', this.selectedFile)
          await this.uploadAvatar(this.selectedFile);
          avatarPath = this.selectedFileName;
        }
        
        console.log('avatarPath:', avatarPath);

        
        const updateData = {
          id: this.user.id,
          nickname: this.user.nickname,
          avatar: avatarPath
        };

        console.log('Sending update request with data:', updateData); // 调试信息

        const response = await axios.post('http://localhost:8000/updateuser', updateData);

        console.log('Update response:', response.data); // 调试信息
        alert('用户信息更新成功！');
        this.toggleEdit();
      } catch (error) {
        console.error('更新用户信息失败:', error);
        alert('更新用户信息失败，请重试。');
      }
    },

    handleEditPassword() {
      console.log("点击了修改密码");
      const userId = localStorage.getItem('userId');
      console.log("当前用户ID:", userId);
      console.log("当前账号的密码是:", this.user.password);

      this.isEditingPassword = true;
      this.$nextTick(() => {
        this.$refs.oldPasswordInput.focus();
      });
    },

    async updatePassword() {
      const userId = localStorage.getItem('userId');
      const oldPassword = this.oldPassword;
      const newPassword = this.newPassword;
      const confirmNewPassword = this.confirmNewPassword;

      if (!userId || !oldPassword || !newPassword || !confirmNewPassword) {
        alert('所有字段都必须填写');
        return;
      }

      if (newPassword !== confirmNewPassword) {
        alert('新密码和确认新密码不一致');
        return;
      }

      // 前端验证旧密码（假设这里有一个简单的验证逻辑）
      if (oldPassword !== this.user.password) {
        alert('旧密码不正确');
        return;
      }

      try {
        const response = await axios.post('http://localhost:8000/updatepassword', {
          id: userId,
          newPassword: newPassword
        });

        console.log('密码更新成功:', response.data);
        alert('密码更新成功！');
        this.isEditingPassword = false;
        this.oldPassword = '';
        this.newPassword = '';
        this.confirmNewPassword = '';
      } catch (error) {
        console.error('密码更新失败:', error);
        alert('密码更新失败，请重试。');
      }
    },

    toggleEdit() {
      this.isEditing = !this.isEditing;
      if (!this.isEditing) {
        location.reload();
      }
    },

    cancelEditPassword() {
      this.isEditingPassword = false;
      this.oldPassword = '';
      this.newPassword = '';
      this.confirmNewPassword = '';
      location.reload();
    }
  }
};
</script>

